import { InjectModel } from '@nestjs/mongoose'
import { ExtractJwt, Strategy } from 'passport-jwt'
import { PassportStrategy } from '@nestjs/passport'
import { Injectable } from '@nestjs/common'
import { ConfigService } from '@nestjs/config'
import { Model } from 'mongoose'
import { UserDocument, User } from '../model/UserSchema.Schema'
@Injectable()
export class NotJwtStrategy extends PassportStrategy(Strategy, 'NotJwt') {
  constructor(
    private readonly configService: ConfigService,
    @InjectModel(User.name) private readonly userSchema: Model<UserDocument>,
  ) {
    super({
      //解析用户提交的header中的Bearer Token数据
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      //加密码的 secret
      secretOrKey: configService.get('TOKEN_SECRET'),
    })
  }

  async validate(playload) {
    const userInfo: { _id: string; username: string; email: string; photo: string | null; createdAt: Date } =
      await this.userSchema.findById({ _id: playload.sub }, '-__v -password -phone -updatedAt')
    return userInfo
  }
}
